<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2019 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://demo.thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\api\controller;

use library\Controller;
use AipOcr;
use library\File;

const APP_ID = '87370094';
const API_KEY = 'MdPgc6TuoKPpoWZR1K0cFrAM';
const SECRET_KEY = 'Jzc5vlIDbVNZQ3L975kJKDrLVcnZtKk7';

/**
 * 百度OCR demo
 * Class demoScript
 * @package app\admin\controller
 */
class Ocr extends ApiBase
{

    /**
     * 病历图片转文字
     */
    public function ocr($url)
    {


        require_once '../vendor/baiduocr/AipOcr.php';
        $client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
        // 调用百度0CR文字识别API
       // 调用通用文字识别, 图片参数为远程url图片
         $result = $client->basicGeneralUrl($url);

        #定义文件名字
        $file_name = explode('.',basename($url));
        $file_url = 'OCR/'.date('Y-m-d').'/'.$file_name[0].".txt";
//        $myfile = fopen($file_url, "w");

        //解析识别结果
        $words = '';
        if(isset($result['words_result'])){
            foreach($result['words_result'] as $word){
                $words .= $word['words'];// . "\n\t" . "\n\t";
                //fwrite($myfile, $word['words'] . "\n\t" . "\n\t");
            }

            $result = $this->glmDoc($words);
            //fclose($myfile);
            $info = File::instance('oss')->save($file_url, $result);
            if (is_array($info) && isset($info['url'])) {

                $data['ocr_url'] = $info['url'];
                $data['words'] = $result;

                return $data;
                //$this->successful('上传成功',$info['url']);
            } else {

                //$this->fail('文件处理失败，请稍候再试！');
                return false;
            }
        } else{
            //$this->fail('失败失败！');
            return false;
        }
        //var_dump($client);die;
    }

    /**
     *
     * 病例转文字
     */
    public function caseToWords($imgUrl = 'https://aiwenzhen.oss-cn-chengdu.aliyuncs.com/20240703/IMAGES/2024-07-03/tmp_b2b49ca52532d4b971c23b2c332719d5.jpg'){

        $url = 'https://ai.inspirvision.cn/s/api/getAccessToken?accessKey=APPID_82X6v97eY11u7F2D&accessSecret=ef79f5a9a464976d5b3635692ebbea02';
        $token = httpGet($url);
        $token = json_decode($token,true);
        if ($token['code'] == 0 && $token['status'] == 200){

            $data = [

                'token'=>$token['data']['access_token'],
                'imgUrl'=>$imgUrl
            ];
            //$header = array("Content-Type: multipart/form-data");
           // $header = array();
            //$res = postJsonCurl($data,'https://ai.inspirvision.cn/s/api/ocr/dischargeAbstract',1,$header);
            $res = post($data,'https://ai.inspirvision.cn/s/api/ocr/dischargeAbstract');
            $res = json_decode($res,true);
            if (isset($res['code']) && $res['code'] == 0){

                $res_data = [];
                $i = 0;
                $j = 0;
                unset($res['data']['section']);
                //unset($res['data']['pmiDischargeDiagnosis']);

                $value = '';
                $pmiAdmissionDiagnosis = '';
              foreach ($res['data'] as $k=>$v){

                  if ($k == 'name'){

                      $res_data[$i]['name'] = '姓名';
                      $res_data[$i]['sort'] = 0;
                  }elseif ($k == 'sex'){;

                      $res_data[$i]['name'] = '性别';
                      $res_data[$i]['sort'] = 1;
                  }elseif ($k == 'age'){

                      $res_data[$i]['name'] = '年龄';
                      $res_data[$i]['sort'] = 2;
                  }elseif ($k == 'id_card_no'){

                      $res_data[$i]['name'] = '证件号码';
                      $res_data[$i]['sort'] = 3;
                  }elseif ($k == 'job'){

                      $res_data[$i]['name'] = '职业';
                      $res_data[$i]['sort'] = 4;
                  }elseif ($k == 'patient_ID'){

                      $res_data[$i]['name'] = '患者ID';
                      $res_data[$i]['sort'] = 5;
                  }elseif ($k == 'medical_record_no'){

                      $res_data[$i]['name'] = '病案号';
                      $res_data[$i]['sort'] = 6;
                  }elseif ($k == 'hospitalization'){

                      $res_data[$i]['name'] = '住院号';
                      $res_data[$i]['sort'] = 4;
                  }elseif ($k == 'patientNumber'){

                      $res_data[$i]['name'] = '门诊号';
                      $res_data[$i]['sort'] = 6;
                  }elseif ($k == 'hospital_name'){

                      $res_data[$i]['name'] = '医院名称';
                      $res_data[$i]['sort'] = 9;
                  }elseif ($k == 'departmentName'){

                      $res_data[$i]['name'] = '科室';
                      $res_data[$i]['sort'] = 10;

                  }elseif ($k == 'physician'){

                      $res_data[$i]['name'] = '医生签名';
                      $res_data[$i]['sort'] = 11;

                  }elseif ($k == 'medicare_type'){

                      $res_data[$i]['name'] = '医保类型';
                      $res_data[$i]['sort'] = 12;

                  }elseif ($k == 'visit_date'){

                      $res_data[$i]['name'] = '就诊日期-门诊病历';
                      $res_data[$i]['sort'] = 13;

                  }elseif ($k == 'treatment_days'){

                      $res_data[$i]['name'] = '住院天数';
                      $res_data[$i]['sort'] = 14;
                  }elseif ($k == 'starttime'){

                      $res_data[$i]['name'] = '入院时间';
                      $res_data[$i]['sort'] = 15;
                  }elseif ($k == 'endtime'){

                      $res_data[$i]['name'] = '出院时间';
                      $res_data[$i]['sort'] = 16;
                  }elseif ($k == 'chief_complaint'){

                      $res_data[$i]['name'] = '主诉';
                      $res_data[$i]['sort'] = 17;
                  }elseif ($k == 'symptomOnsetTime'){

                      $res_data[$i]['name'] = '自述症状发生时间';
                      $res_data[$i]['sort'] = 18;
                  }elseif ($k == 'pmiAdmissionDiagnosis'){

                      $res_data[$i]['name'] = '现疾病-入院诊断';
                      $res_data[$i]['sort'] = 19;
                  }elseif ($k == 'pmiDischargeDiagnosis'){

                      $res_data[$i]['name'] = '现疾病-出院诊断';
                      $res_data[$i]['sort'] = 20;
                  }elseif ($k == 'pmiCheckDesc'){

                      $res_data[$i]['name'] = '现疾病-检查描述';
                      $res_data[$i]['sort'] = 21;
                  }elseif ($k == 'pmiDiseaseDesc'){

                      $res_data[$i]['name'] = '现疾病描述';
                      $res_data[$i]['sort'] = 22;
                  }elseif ($k == 'pmisurgicalHistory'){

                      $res_data[$i]['name'] = '现疾病-手术操作';
                      $res_data[$i]['sort'] = 23;
                  }elseif ($k == 'pmhCheckDesc'){

                      $res_data[$i]['name'] = '既往病史-检查描述';
                      $res_data[$i]['sort'] = 24;
                  }elseif ($k == 'pmhDiseaseDesc'){

                      $res_data[$i]['name'] = '既往病史-疾病描述';
                      $res_data[$i]['sort'] = 25;
                  }elseif ($k == 'pmhSurgicalHistory'){

                      $res_data[$i]['name'] = '既往病史-手术操作';
                      $res_data[$i]['sort'] = 26;
                  }elseif ($k == 'angle'){

                      $res_data[$i]['name'] = '旋转角度';
                      $res_data[$i]['sort'] = 27;
                  }else{

                      $res_data[$i]['name'] = '';
                      $res_data[$i]['sort'] = 28;
                  }
                  if ($v){


                      if ($k == 'pmiCheckDesc' || $k == 'pmiDiseaseDesc' || $k == 'pmisurgicalHistory' ||
                          $k == 'pmhCheckDesc' || $k == 'pmhDiseaseDesc' || $k == 'pmhSurgicalHistory'){
                          $res_data[$i]['value'][$i][$j]['time'] = [];
                          $res_data[$i]['value'][$i][$j]['desc'] = [];
                          foreach ($v as $kk=>$vv){
                              if ($vv['desc']){

                                  $value .= $vv['desc']['final'].'  ';
                              }
                              if ($vv['time']){

                                  //$res_data[$i]['value'][$i][$j]['time'] = $vv['time']['final'];
                                  $value .= $vv['time']['final']."\n\t";
                              }


                          }
                          $res_data[$i]['value'] = $value;
                      }else{
                          if ($k == 'pmiAdmissionDiagnosis' || $k == 'pmiDischargeDiagnosis'){


                              if ($v){

                                  foreach ($v as $vv){

                                      $pmiAdmissionDiagnosis .= $vv['final']."\n\t";
                                  }
                              }

                              $res_data[$i]['value'] = $pmiAdmissionDiagnosis;
                          }else{

                              $res_data[$i]['value'] = $v['final'];
                          }


                      }
                  }else{

                      $res_data[$i]['value'] = '';
                  }


                  $i++;

              }

                array_multisort(array_column($res_data,'sort'),SORT_ASC,$res_data);

                $file_name = explode('.',basename($imgUrl));
                $file_url = 'OCR/'.date('Y-m-d').'/'.$file_name[0].".txt";
                $words = "\n\t";
                foreach($res_data as $v){
                    $words .= $v['name'].'：'.$v['value'] . "\n\t" . "\n\t";
                    //fwrite($myfile, $word['words'] . "\n\t" . "\n\t");
                }
                $info = File::instance('oss')->save($file_url, $words);
                if (is_array($info) && isset($info['url'])) {

                    $result['ocr_url'] = $info['url'];
                    $result['words'] = $res_data;//json_encode($res_data,true);

                    return $result;
                    //$this->successful('上传成功',$info['url']);
                } else {

                    //$this->fail('文件处理失败，请稍候再试！');
                    return false;
                }

                return $res_data;
            }else{

                return false;
            }

        }else{

            return false;
        }

    }

    /**
     *
     * 智普GLM-4整理文档
     */
    public function glmDoc($content){

        //$content = '人诸暨市人民医院温州医科大学附属诸暨医院940出院记录姓名：宜志勇科室：呼吸与危重症医学利三病房：20楼西床号，5年龄，42岁住院号：800394901出院日期：2024年03月14日10时21分住院天数：3天入院日期：2024年03月11日13时44分过敏情况：无治疗转归：好转自动出院：否本次植入物（是否可MR):无病理号：无入院诊断：1，恶性肿瘤联合治疗后的随诊检查2，右肺恶性肿瘤腺癌：T4N2M1c(脑干)IV期3，脑干继发恶性肿病理诊断：无瘤4.2型糖尿病5.肾积水伴肾结石6.前列腺钙化灶出院诊断：1.恶性肿瘤联合治疗后的随诊检查2，右肺恶性肿瘤腺癌：T4N2M1c(脑干)V期3，脑干继发恶性肿瘤4.2型糖尿病5，肾积水伴肾结石6.前列腺钙化灶入院情况：患者因“明确肺癌1年”入院。专科情况：末梢血氧97%，神志清，精神可，颈软，气管居中，浅表淋巴结未及肿大，成人胸，听诊双肺呼吸音清，未及干湿性啰音，心律齐，未及病理性杂音，腹软，无压痛反跳痛，肝脾肋下未及，神经系统检查无殊，双肢轻度凹陷性浮肿。辅助检查：暂无。1、主要治疗：1，完善各项辅检，如血常规、肿瘤标志物、胸部CT、彩超等辅检评估病情：2，治疗上自备予赛住院经过：沃替尼片400mg每天1次口服靶向抗肿瘤，控制血糖等对症处理，并根据病情变化及时调整治疗方案。3.患者无2、主要检查结果：2024-3-11：BGA:pH7.381,二氧化碳分压44.9mmHg,氧分压85.3mmHg,肺泡-动脉氧分压差癌痛。暂不子止痛处理。14.7mmig,p02/FI02406mmHg/%,AG!7.5mmol/L。血常规：白细胞计数19,7x109/L,中性粒细胞分类↑0.77。血型B型，阳阳性，急诊肌钙蛋白-1正常。凝血谱：正常。D-二聚体正常。2024-3-12：C反应蛋白正常。电解质：正常。肝功能：GGT1277U/L。肾功能：尿酸1518umo1/L。血脂：总胆固醇16.22mmo1/九，甘油三脂↑6.31mmol/L。HDL-C(0.84mol/L,即刻糖↑8.88mmol/L,BNP正常。肿瘤指标：AFP、CEA、Cal25、Ca199、PSA、fPSA、SE、CYFRA2I1、SCC正常，Pro-GRP182.8pg/mL。甲状腺功能：TT3、TT4、FT3、FT4、TSH、Anti-TPO、TG-Ab、TRAb正常。乙肝三系：均为阴性。尿常规：基本正常。2024-3-13：ANM:均为阴性。ANCA:均为阴性。感染四项：均为阴性。2024-03-12胸部CT平扫检查报告：检查结果右肺上叶Ca治疗后复查病例，纵隔淋巴结增大，对照2023-12-08变化不大，请结合临床及复查。两肺散在微小实性结节，考虑增殖灶可能。2024-03-3双侧锁骨上淋巴结彩超检查报告；检查结果二尖瓣轻度反流。肝胆脾胰彩超检查报告：检查结果1肝回声细密。2.胰腺回声偏强。颈部淋巴结彩超检查报告：检查结果1.双侧颈部多发淋巴结探及。2.右肾轻度积水。3.双肾多发结石。4.前列腺多发钙化灶。左下肢动脉彩超检查报告：检查结果上述。头颅平扫+增强+DWI检查报告：检查结果脑干右侧、右侧额叶转移瘤，与前片2023-12-08比较病灶增大。第4脑室扩张。左侧脑室旁少量缺血灶。右侧后顶部皮下软组织内囊肿。3、手术名称及术中主要所见：无。出院情况：患者无头痛头晕，无肢体活动障碍，无明显咳嗽咳痰，无胸闷气促，无胸痛心悸，无发热畏寒，精神、胃纳可。查体：神志清，精神可，成人胸，听诊双肺呼吸音清，未及干湿性啰音，心律齐，未及病理性杂音，腹软，无压痛反跳痛，肝脾肋下未及，双下肢轻度浮肿。出院医嘱：第1页';
            // 设置API密钥和URL
            $api_key = 'ab96fe15c76978c873cb7a9bbfb59ac5.jqJVsSyPPNXN4kiZ';
            $url = 'https://open.bigmodel.cn/api/paas/v4/chat/completions'; // 请替换为实际的API端点

            // 设置请求的参数
            $data = [
                'model' => 'glm-4',
                'messages' => [
                      [
                       'role'=>'user',
                       'content'=>$content
                       ]
                ],
                //'outputMode' => 'json', // 根据需要提取的信息类型设置'text' => $doc,
                // 其他必要的参数
            ];

            $headers = array("Authorization: Bearer {$api_key}","Content-Type: application/json");

           $res = postJsonCurl($data,$url,1,$headers);
           $res = json_decode($res,true);
           return $res['choices'][0]['message']['content'];
    }

}
